package com.wuwei.elearning.utils.result;

import lombok.Data;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//统一返回结果类
@Data
public class Result<T> {

    private Integer code; //状态码

    private String message; //返回状态信息（成功 失败）

    private T data; //返回数据

    public Result() {}

    // 统一错误响应方法
    public static void sendErrorResponse(HttpServletResponse response, String message, int httpStatus) throws IOException {
        response.setStatus(httpStatus);
        response.setContentType("application/json;charset=UTF-8");
        String jsonResponse = String.format("{\"message\": \"%s\"}", message);
        response.getWriter().write(jsonResponse);
    }


    //成功的方法，有data数据
    public static<T> Result<T> ok(T data) {
        Result<T> result = new Result<>();
        if(data != null) {
            result.setData(data);
            if (data instanceof String) {
                // 如果T对象是String类型，则进行特定处理
                String strData = (String) data;
                result.setMessage(strData);
            }
        }
        result.setCode(20000);
        return result;
    }

    //失败的方法,有data数据
    public static<T> Result<T> fail(T data) {
        Result<T> result = new Result<>();
        if(data != null) {
            result.setData(data);
            if (data instanceof String) {
                // 如果T对象是String类型，则进行特定处理
                String strData = (String) data;
                result.setMessage(strData);
            }
        }
        result.setCode(20001);
        return result;
    }

    public Result<T> message(String msg){
        this.setMessage(msg);
        return this;
    }

    public Result<T> code(Integer code){
        this.setCode(code);
        return this;
    }
}
